//
//  UserinfoViewController.m
//  ChatDemo-UI2.0
//
//  Created by zz on 16/5/13.
//  Copyright © 2016年 zz. All rights reserved.
//

#import "UserinfoViewController.h"
#import "UserinfoTableViewCell.h"
#import "contractsBtn.h"
#import "XZHeaderImageView.h"
#import "CreateImageViewController.h"
@class ApplyEntity;
@interface UserinfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>

@end

@implementation UserinfoViewController{
    
    UIWebView *phoneCallWebView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.edgesForExtendedLayout = UIRectEdgeAll;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //＊＊＊＊＊＊＊delete by zz （16.05.19）［逻辑修改了，老师也不能在打电话］＊＊＊＊＊＊＊＊＊＊
    
    /*
    NSDictionary *dic = [Utils acquirePersonalImformationFromMemoryWithPersonID:USERID];
    NSDictionary *userinfoDic = [dic objectForKey:@"userinfo"];
    int lasttype = [[userinfoDic objectForKey:@"lasttype"] intValue];
    if (lasttype == 1) {
        _isTeacher = YES;
    }else{
        _isTeacher = NO;
    }
     */
    
    _isTeacher = NO;
    //＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊End＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊＊

    
    int isaddfriend = [[_infoDic objectForKey:@"isaddfriend"] intValue];
    if (isaddfriend == 1) {
        _isFriend = YES;
    }else{
        _isFriend = NO;
    }
    
    //1.初始化UI
    [self configureUI];
}

-(void)back{
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)configureUI{
    
    
    UIView *bgView = [[UIView alloc] init]; //蓝色的背景view
    bgView.backgroundColor = RGBACOLOR(72, 180, 255, 1);
    
    //返回按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageWithOriginalName:@"jiantou_grxx_1_nor"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(15, 20, 44, 44);
    [bgView addSubview:backBtn];
    
    XZHeaderImageView *headView = [[XZHeaderImageView alloc]initWithFrame:CGRectMake((SCREENWIDTH - 70)/2, 88, 70, 70)];
    headView.clipsToBounds = YES;
    headView.contentMode = UIViewContentModeScaleAspectFill;
    headView.layer.cornerRadius = 35;
    
    //头像
    NSString *logo = [_infoDic objectForKey:@"logo"];
    int logoType = [[_infoDic objectForKey:@"logotype"] intValue];
    if (![logo hasPrefix:@"http"] && logo != nil) {
        logo = [REQUESTIMAGEURL stringByAppendingString:logo];
    }
    [headView.headImage sd_setImageWithURL:[NSURL URLWithString:logo]];
    
    //昵称
    NSString *username = [_infoDic objectForKey:@"username"];
    
    if (username.length > 2) {
        username = [username substringFromIndex:username.length - 2];
    }
    headView.namelabel.font = [UIFont systemFontOfSize:15];
    headView.namelabel.text = username;
    
    headView.flag = logoType == 1?YES:NO;
    
    [bgView addSubview:headView];
    
    UILabel *nameLabel = [[UILabel alloc] init];
    nameLabel.textColor = [UIColor whiteColor];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.font = [UIFont systemFontOfSize:17];
    nameLabel.text = [_infoDic objectForKey:@"username"];
    [bgView addSubview:nameLabel];
    
    [self.view addSubview:bgView];
    
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(headView.mas_bottom).offset(20);
        make.height.equalTo(@20);
        make.width.equalTo(@300);
        make.centerX.equalTo(headView.mas_centerX).offset(0);
        
    }];
    
    [bgView mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.top.equalTo(self.view.mas_top).offset(0);
        make.height.equalTo(@220);
    }];
    
    _table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    _table.tableFooterView = [[UIView alloc] init];
    [self.view addSubview:_table];
    
    [_table mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(bgView.mas_bottom).offset(0);
        make.left.equalTo(bgView.mas_left).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(-49);
        make.right.equalTo(self.view.mas_right).offset(0);
    }];
    
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor clearColor];
    
    bottomView.frame = CGRectMake(0, VIEW_HEIGHT - 49, VIEW_WIDTH, 49);
    
    contractsBtn *addBtn = [[contractsBtn alloc] initWithImage:@"jiahaoyou_grxx_5_nor" andTitle:@"加好友"];
    addBtn.tag = 1;
    [addBtn addTarget:self action:@selector(addFriend:) forControlEvents:UIControlEventTouchUpInside];
    addBtn.frame = [self getFrameWithIsteacher:_isTeacher andIsfriend:_isFriend andTag:1];
    [self.view addSubview:addBtn];

    contractsBtn *phoBtn = [[contractsBtn alloc] initWithImage:@"dadianhua_grxx_6_nor" andTitle:@"打电话"];
    phoBtn.tag = 2;
    phoBtn.frame = [self getFrameWithIsteacher:_isTeacher andIsfriend:_isFriend andTag:2];
    if (_isTeacher == YES) {
        phoBtn.hidden = NO;
    }else{
        phoBtn.hidden = YES;
    }
    
    if (_isFriend == YES) {
        addBtn.hidden = YES;
    }else{
        addBtn.hidden = NO;
    }
    
    [phoBtn addTarget:self action:@selector(phoneCall:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:phoBtn];
    
    contractsBtn *msgBtn = [[contractsBtn alloc] initWithImage:@"faxiaoxi_grxx_7_nor" andTitle:@"发消息"];
    msgBtn.tag = 3;
    msgBtn.frame = [self getFrameWithIsteacher:_isTeacher andIsfriend:_isFriend andTag:3];
    [msgBtn addTarget:self action:@selector(sendMsg:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:msgBtn];
    
}

-(CGRect)getFrameWithIsteacher:(BOOL)isteacher andIsfriend:(BOOL)isFriend andTag:(int)tag{
    
    CGFloat x,y,w,h;
    y = VIEW_HEIGHT - 49;
    h = 49;
    if (isFriend) {
        
        if (isteacher) {
            
            if (tag == 2) { //
                
                x = 0;
                w = VIEW_WIDTH/2;
                
            }else if (tag == 3){
                
                x = VIEW_WIDTH/2;
                w = VIEW_WIDTH/2;
            }
            
        }else{
            
            if (tag == 3) {
                
                x = 0;

                w = VIEW_WIDTH;

            }
            
        }
        
    }else{
        
        if (isteacher) {
            
            w = VIEW_WIDTH/3;
            
            if (tag == 1) {
                x = 0;
            }else if (tag == 2){
                x = w * (tag - 1);
            }else if(tag == 3){
                x = w * (tag - 1);
            }
            
        }else{
            
            w = VIEW_WIDTH/2;
            if (tag == 1) {
                x = 0;
            }else if (tag == 3){
                x = w;
            }
        }
    }
    
    CGRect frame = CGRectMake(x, y, w, h);
    return frame;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (_isTeacher) {
        return 5;
    }else{
        return 4;
    }
    //return 4;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UserinfoTableViewCell *cell = [[UserinfoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"123"];
    
    NSString *topStr;
    NSString *botStr;
    
    int sexType = [[_infoDic objectForKey:@"usersex"] intValue];
    
    switch (indexPath.row) {
        case 0:
            topStr = [_infoDic objectForKey:@"username"];
            botStr = @"姓名";
            break;
        case 1:
            topStr = sexType == 0?@"男":@"女";
            botStr = @"姓别";
            cell.twoDimension.hidden = YES;
            break;
        case 2:
            topStr = [_infoDic objectForKey:@"birthday"];
            botStr = @"生日";
            cell.twoDimension.hidden = YES;
            break;
        case 3:
            topStr = [[_infoDic objectForKey:@"userid"] stringValue];
            botStr = @"师云号";
            cell.twoDimension.hidden = YES;
            break;
        case 4:
            topStr = [_infoDic objectForKey:@"mobile"];
            botStr = @"电话";
            cell.twoDimension.hidden = YES;
            break;
            
        default:
            break;
    }
    
    cell.topLabel.text = topStr;
    cell.bottomLabel.text = botStr;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}




#pragma mark -UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 59;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 20;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (section == 0) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 36)];
        view.backgroundColor = [UIColor whiteColor];
        
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(17, 11, 200, 15)];
        titleLabel.font = [UIFont boldSystemFontOfSize:15];
        titleLabel.textColor = RGBACOLOR(56, 173, 255, 1);
        titleLabel.text = @"个人信息";
        [view addSubview:titleLabel];
        return view;
    }else{
        return nil;
    }
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
        NSString *userid = [[_infoDic objectForKey:@"userid"] stringValue];
        
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        
        CreateImageViewController * view = (CreateImageViewController *)[storyboard instantiateViewControllerWithIdentifier:@"CreateImageViewController"];
        view.displayStr = [NSString stringWithFormat:@"http://admin.our100.net/DownloadAPP.aspx?<**>yh%@",userid];
        [self.navigationController pushViewController:view animated:YES];

    }
}

#pragma mark -响应事件
//加好友
-(void)addFriend:(id)sender{
    
    //不能添加自己为好友
    if ([[[_infoDic objectForKey:@"userid"] stringValue] isEqualToString:USERID]) {  //添加的用户是自己
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:NSLocalizedString(@"friend.notAddSelf", @"can't add yourself as a friend") delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
        [alertView show];
        
        return;
    }
    
    if (_isFriend) {
        
        [Utils alertViewWithMessage:@"对方已经是您的好友"];
        return;
    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil
                                                    message:NSLocalizedString(@"saySomething", @"say somthing")
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"cancel", @"Cancel")
                                          otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
    [alert setAlertViewStyle:UIAlertViewStylePlainTextInput];
    UITextField *field = [alert textFieldAtIndex:0];
    field.returnKeyType = UIReturnKeySend;
    [field addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [alert show];

    
    //判断是否已发来申请
    //NSArray *applyArray = [[ApplyViewController shareController] dataSource];
    //if (applyArray && [applyArray count] > 0) {
        //for (ApplyEntity *entity in applyArray) {
            //ApplyStyle style = [entity.style intValue];
            //BOOL isGroup = style == ApplyStyleFriend ? NO : YES;
            //if (!isGroup && [entity.applicantUsername isEqualToString:_textField.text]) {
                //NSString *str = [NSString stringWithFormat:NSLocalizedString(@"friend.repeatInvite", @"%@ have sent the application to you"), _textField.text];
                //UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt") message:str delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
                //[alertView show];
                
                //return;
            //}
        //}
    //}

}

//打电话
-(void)phoneCall:(id)sender{
    
    NSString *phoneNum = [_infoDic objectForKey:@"mobile"];// 电话号码
    
    //phoneNum = [phoneNum stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNum]];
    
    if ( !phoneCallWebView ) {
        phoneCallWebView = [[UIWebView alloc]initWithFrame:CGRectZero];// 这个webView只是一个后台的容易 不需要add到页面上来 效果跟方法二一样 但是这个方法是合法的
    }
    
    [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];

}

//发消息
-(void)sendMsg:(id)sender{

    
}

-(void)textFieldDidChange:(UITextField *)field{
    
    if (field.text.length > 8) {
        field.text = [field.text substringToIndex:9];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([alertView cancelButtonIndex] != buttonIndex) {
        UITextField *messageTextField = [alertView textFieldAtIndex:0];
        
        NSDictionary *dic = [Utils acquirePersonalImformationFromMemoryWithPersonID:USERID];
        
        NSDictionary *userInfoDic = [dic objectForKey:@"userinfo"]; //用户资料
        NSString *logoStr = [userInfoDic objectForKey:@"logo"]; //头像
        NSString *nameStr = [userInfoDic objectForKey:@"username"]; //昵称
        if (![logoStr hasPrefix:@"http"]) {
            logoStr = [NSString stringWithFormat:@"%@%@",REQUESTIMAGEURL,logoStr];
        }
        NSString *logoType = [userInfoDic objectForKey:@"logotype"];
        
        NSString *messageStr = @"";
        //NSDictionary *loginInfo = [[[EaseMob sharedInstance] chatManager] loginInfo];
        //NSString *username = [loginInfo objectForKey:kSDKUsername];
        if (messageTextField.text.length > 0) {
            //messageStr = [NSString stringWithFormat:@"%@：%@", username, messageTextField.text];
            messageStr = [NSString stringWithFormat:@"{\'%@\':\'%@\',\'%@\':\'%@\',\'%@\':\'%@\',\'%@\':\'%@\'}",@"verifyInfo",messageTextField.text,@"logo",logoStr,@"userName",nameStr,@"logo_type",logoType];
        }
        else{
            messageStr = [NSString stringWithFormat:@"{\'%@\':\'%@\',\'%@\':\'%@\',\'%@\':\'%@\',\'%@\':\'%@\'}",@"verifyInfo",[NSString stringWithFormat:@"我是%@",nameStr],@"logo",logoStr,@"userName",nameStr,@"logo_type",logoType];
        }

        [self sendFriendApplyWithUserId:[[_infoDic objectForKey:@"userid"] stringValue] message:messageStr];
    }

}

- (void)sendFriendApplyWithUserId:(NSString *)buddyName
                          message:(NSString *)message
{
    
    if (buddyName && buddyName.length > 0) {
        [self showHudInView:self.view hint:NSLocalizedString(@"friend.sendApply", @"sending application...")];
//        EMError *error;
//        [[EaseMob sharedInstance].chatManager addBuddy:buddyName message:message error:&error];
        [self hideHud];

//        if (error) {
//            [self showHint:NSLocalizedString(@"friend.sendApplyFail", @"send application fails, please operate again")];
//        }
//        else{
//            [self showHint:NSLocalizedString(@"friend.sendApplySuccess", @"send successfully")];
//            [self.navigationController popViewControllerAnimated:YES];
//        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

-(void)viewWillDisappear:(BOOL)animated{
    self.navigationController.navigationBar.hidden = NO;
    [super viewWillDisappear:animated];
}

@end
